package project2011;


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.lang.Object.*;
import java.applet.Applet.*;
import java.util.*;


/**
 * Manages GUI functionality
 * @author Gilles
 */


public class GUI {
    private POS pos;
    JFrame frame = new JFrame();;
    JPanel p,p2;
    JTextField  userNameTF;
    JPasswordField passwordTF;
    int productIndex;
    double total = 0.0;
    User user;
    Seller seller;
    ArrayList<Product> cart = new ArrayList<Product>();
    ArrayList<Integer> qty = new ArrayList<Integer>();
    
    /**
     * A constructor for GUI initiates pos and calls the loginFrame
     * @param POS the point of sale system to be used with this GUI
     */
    public GUI(POS pos){
        this.pos = pos;
        makeLoginFrame();
    }
 
  
    /**
     * this function creates the Login Frame...
     */
    public final void makeLoginFrame(){

        
        frame.setTitle("Please Log In");
        
        //Create and populate the panel.
        p = new JPanel(new GridLayout(3,0));            
        
        JLabel userNameLabel = new JLabel("User Name: ", JLabel.TRAILING);
        p.add(userNameLabel);
        userNameTF = new JTextField(10);
        userNameLabel.setLabelFor(userNameTF);
        p.add(userNameTF);
        
        JLabel passwordLabel = new JLabel("Password: ", JLabel.TRAILING);
        p.add(passwordLabel);
        passwordTF = new JPasswordField(10);
        passwordLabel.setLabelFor(passwordTF);
        p.add(passwordTF);

        JLabel l = new JLabel("", JLabel.TRAILING);
        p.add(l);
        
        JButton login = new JButton("Login!");
        l.setLabelFor(login);
        p.add(login);
        
        login.addActionListener(new login());
        
        //Create and set up the window.
        
        finishFrame();   
    }  

    /**
     * This adds a few functions to the frame and displays it
     */
    public void finishFrame(){

        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane.
        frame.setContentPane(p);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    
    /**
     * This is the home page for Users
     * @param userName the user name
     */
    public void userHome(String userName){

        frame.setTitle(userName + " Home Page");
        
        /**
         * adding the buttons to the panel
         */
        p = new JPanel(new GridLayout(1,4));
        JLabel welcome = new JLabel("Welcome " + userName,JLabel.CENTER);
        p.add(welcome);
        
        JButton viewShopCRT = new JButton("Shopping Cart");
        p.add(viewShopCRT);
        
        JButton viewProdList = new JButton("Product List");
        p.add(viewProdList);
        
        JButton logout = new JButton("Log Out");
        p.add(logout);
        
        //Action Listeners for user interactions wit the buttons
        viewShopCRT.addActionListener(new viewShopCRT());
        viewProdList.addActionListener(new viewProdList());
        logout.addActionListener(new logout());
  
        finishFrame();      
    }   
    
    /*
     * This is the Home page for the Seller
     * @param String the user name
     */
    public void sellerHome(String userName){
        
        frame.setTitle(userName + " Home Page");
        p = new JPanel(new GridLayout(1,4));
        JLabel welcome = new JLabel("Welcome " + userName,JLabel.CENTER);
        p.add(welcome);
        
        JButton viewBank = new JButton("View Bank");
        p.add(viewBank);
        
        JButton viewInventory = new JButton("My Inventory");
        p.add(viewInventory);
        
        JButton logout = new JButton("Log Out");
        p.add(logout);
        
        //Action listeners
        viewBank.addActionListener(new viewBank());
        viewInventory.addActionListener(new viewInventory());
        logout.addActionListener(new logout());

        finishFrame();    
    }
        
    
    /**
     * This Frame will show the product list in a list
     * using a JList from which the user can select a
     * given product just by clicking on it. 
     */        
    public void showProductList(){

        frame.setTitle("Product List");
        
        p= new JPanel (new BorderLayout());
        p2 = new JPanel(new BorderLayout());
        
        JButton viewShopCRT = new JButton("Shopping Cart");
        p2.add(viewShopCRT,BorderLayout.WEST);
        
        JButton logout = new JButton("Log Out");
        p2.add(logout,BorderLayout.EAST);
        
        DefaultListModel listModel = new DefaultListModel();
        
        /*
         * for loop that adds the products to the JList
         */
        for(Product x: pos.inventory.queue)
        {
            listModel.addElement(x.getProductName());
        }
       
        final JList list = new JList(listModel);
        
        /*
         * Action listener for the list.
         * if the user clicks on a product it is called
         */
        list.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
            productPage(pos.inventory.queue.get(list.getSelectedIndex()));
            }
        });
        
         
        //List will show 8 rows
        list.setVisibleRowCount(8);
        JScrollPane listScrollPane = new JScrollPane(list);
        
        viewShopCRT.addActionListener(new viewShopCRT());
        logout.addActionListener(new logout());
        
        
        p.add(listScrollPane,BorderLayout.CENTER);
        p.add(p2,BorderLayout.SOUTH);
        
        
        frame.add(p);
        
        finishFrame();      
    }
    /**
     * This frame shows the Users shopping Cart
     * the user may decide to change the qty of 
     * one of the products or modify the cart
     * by clicking on update cart.
     */
    public void showShoppingCRT(){

        total =0.0;
        frame.setTitle("Shopping Cart");
        p = new JPanel(new GridLayout(cart.size()+1,5));
        int temp = 0;
        
        /**
         * for loop that loads all chosen products into JLabels
         */
        for(Product x: cart)
        {
            
            JLabel productName = new JLabel(x.getProductName(),JLabel.TRAILING);
            p.add(productName);

            JLabel productUPC = new JLabel(Integer.toString(x.getUPC()),JLabel.TRAILING);
            p.add(productUPC);

            JLabel productPrice = new JLabel("$"+Double.toString(x.getPrice()),JLabel.TRAILING);
            p.add(productPrice);

            JLabel qtyLabel = new JLabel("Qty: " +qty.get(temp).toString(), JLabel.TRAILING);
            p.add(qtyLabel);
            
            double mult = Integer.parseInt(qty.get(temp).toString())*x.getPrice();
            JLabel price = new JLabel("$" +Double.toString(mult) + "  ", JLabel.TRAILING);
            p.add(price);
            
            total = total + Integer.parseInt(qty.get(temp).toString())*x.getPrice();
            temp++;
        }
        JButton updateCRT = new JButton("Update Cart");
        p.add(updateCRT);

        JButton checkOut = new JButton("Check Out!");
        p.add(checkOut);
        
        JButton viewProdList = new JButton("Product List");
        p.add(viewProdList);
        
        JButton logout = new JButton("Log Out");
        p.add(logout);
        
        JLabel totalLabel = new JLabel("total: $" + Double.toString(total) + "  ", JLabel.TRAILING);
        p.add(totalLabel);
        
        //Action Listeners
        updateCRT.addActionListener(new updateCRT());
        checkOut.addActionListener(new checkout());
        viewProdList.addActionListener(new viewProdList());
        logout.addActionListener(new logout());
        
        finishFrame();
    }
    /**
     * This frame will show the sellers inventory in a JList
     */
    public void showInventory(){

        frame.setTitle( userNameTF.getText() + " Inventory");
        
        p= new JPanel (new BorderLayout());
        p2 = new JPanel(new BorderLayout());
        
        JButton menu = new JButton("Go to Menu");
        p2.add(menu,BorderLayout.WEST);
        
        JButton logout = new JButton("Log Out");
        p2.add(logout,BorderLayout.EAST);
        
        DefaultListModel listModel = new DefaultListModel();
        
        //for loop loadin the list, with product name and price
        for(Product x: pos.inventory.queue)
        {
            if(x.getVendorName().equals(userNameTF.getText())){
                listModel.addElement(x.getProductName()+ " $" + Double.toString(x.getPrice()));
            }
        }
       
        final JList list = new JList(listModel);
        
        /**
         * Action listeners for list and the buttons
         */
        list.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e){
            productInvPage(pos.inventory.queue.get(list.getSelectedIndex()));
            }
        });  
        
        list.setVisibleRowCount(8);
        JScrollPane listScrollPane = new JScrollPane(list);
       
        menu.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                clearFrame();
                sellerHome(userNameTF.getText());
                
            }
        });
        logout.addActionListener(new logout());
        
        
        p.add(listScrollPane,BorderLayout.CENTER);
        p.add(p2,BorderLayout.SOUTH);
        
        
        frame.add(p);
        
        finishFrame();
    }
    /**
     * This Frame shows the product's info
     * to the user. he is able to select a 
     * qty and add to his shopping cart.
     * @param product the product to display
     */
    public void productPage(final Product product){        

        frame.setTitle(product.getProductName());
        
        p = new JPanel(new GridLayout(2,4));
        JLabel productName = new JLabel(product.getProductName(),JLabel.TRAILING);
        p.add(productName);
        
        JLabel productUPC = new JLabel(Integer.toString(product.getUPC()),JLabel.TRAILING);
        p.add(productUPC);
        
        JLabel productPrice = new JLabel(Double.toString(product.getPrice()),JLabel.TRAILING);
        p.add(productPrice);
        
        JLabel userNameLabel = new JLabel("Qty: ", JLabel.TRAILING);
        p.add(userNameLabel);
        final JTextField qtyTF = new JTextField(3);
        String defaultQty = "1";
        if(cart.contains(product)){
            defaultQty = qty.get(cart.indexOf(product)).toString();
            qty.set(cart.indexOf(product), 0);
        }
        qtyTF.setText(defaultQty);
        userNameLabel.setLabelFor(qtyTF);
        p.add(qtyTF);
        
        
        
        JButton addToCRT = new JButton("Update Cart");
        p.add(addToCRT);

        JButton viewShopCRT = new JButton("Shopping Cart");
        p.add(viewShopCRT);
        
        JButton viewProdList = new JButton("Product List");
        p.add(viewProdList);
        
        JButton logout = new JButton("Log Out");
        p.add(logout);
        
        /*
         * Action listeners
         */
        addToCRT.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                
                int a = Integer.parseInt(qtyTF.getText());
                
                /* 
                 * if else statement taking care of adding elements
                 * into the cart if its not there already or update 
                 * if it is
                 */
                
                if (cart.contains(product))
                {
                    a=Integer.parseInt(qty.get(cart.indexOf(product)).toString()) + Integer.parseInt(qtyTF.getText());
                    qty.set(cart.indexOf(product), a);
                    
                    
                }
                else{
                    qty.add(a);
                    cart.add(product);
                }
                showProductList();
            }
        });
        viewShopCRT.addActionListener(new viewShopCRT());
        viewProdList.addActionListener(new viewProdList());
        logout.addActionListener(new logout());
        
        
        finishFrame();
    }
        /**
         * This frame Show the product to the seller and 
         * allows him to change the price
         */
    public void productInvPage(final Product product){   

       
        frame.setTitle(product.getProductName());
        p = new JPanel(new GridLayout(2,4));
        JLabel productName = new JLabel(product.getProductName(),JLabel.TRAILING);
        p.add(productName);
        
        JLabel productUPC = new JLabel(Integer.toString(product.getUPC()),JLabel.TRAILING);
        p.add(productUPC);
        
        JLabel userNameLabel = new JLabel("Price: ", JLabel.TRAILING);
        p.add(userNameLabel);
        final JTextField priceTF = new JTextField(3);
        String defaultPrice = Double.toString(product.getPrice());
        
        priceTF.setText(defaultPrice);
        userNameLabel.setLabelFor(priceTF);
        p.add(priceTF);
        
        JButton changePrice = new JButton("Update Price");
        p.add(changePrice);

        JButton profit = new JButton("View Bank");
        p.add(changePrice);
        
        JButton viewInventory = new JButton("My Inventory");
        p.add(viewInventory);
        
        JButton logout = new JButton("Log Out");
        p.add(logout);
        
        /*
         * Action listener
         */
        changePrice.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){ 
                double a = Double.parseDouble(priceTF.getText());
                pos.inventory.changePrice(product, a);
                showInventory();
            }
        });  
        logout.addActionListener(new logout());
        profit.addActionListener(new viewBank());
        viewInventory.addActionListener(new viewInventory());
        
        finishFrame();
    }
    /**
     * this clears the frame
     */
    public void clearFrame(){

        frame.getContentPane().removeAll();
        frame.getContentPane().repaint();
    }
    
    /**
     * this frame will display for the seller his bank information,
     * his profits.
     */
    public void displayBank(){

        frame.setTitle(userNameTF.getText() + " Bank");
        
        p= new JPanel (new BorderLayout());
        p2 = new JPanel(new BorderLayout());
        
        JButton menu = new JButton("Go to Menu");
        p2.add(menu,BorderLayout.WEST);
        
        JButton viewInventory = new JButton("My Inventory");
        p2.add(viewInventory,BorderLayout.CENTER);
        
        JButton logout = new JButton("Log Out");
        p2.add(logout,BorderLayout.EAST);
        
        viewInventory.addActionListener(new viewInventory());
        logout.addActionListener(new logout());
        menu.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                clearFrame();
                sellerHome(userNameTF.getText());
                
            }
        });
        
        Seller Vendor = pos.findSeller(userNameTF.getText());               
        JLabel bankLabel = new JLabel("    You have $" + Double.toString(pos.bank.find(Vendor.getAccountNumber()).getBalance()) + " in your account!    ");
                   
        p.add(bankLabel, BorderLayout.NORTH);
        p.add(p2,BorderLayout.SOUTH);
        
        
        frame.add(p);
        
        finishFrame();      
    }
    
    /**
     * will clear the frame and call the shopping cart frame
     */
    public class viewShopCRT implements ActionListener{
        public void actionPerformed(ActionEvent e){

            clearFrame();
            showShoppingCRT();
        }
    }   
    /**
     * will allow the user to tnter his credit card number
     * and to check out
     */
    public class checkout implements ActionListener{
        public void actionPerformed(ActionEvent e){

            clearFrame();
            
            frame.setTitle(user.getName() + " Checkout Page");
            p = new JPanel(new GridLayout(4,2));

            JLabel welcome = new JLabel("Your total is: " + Double.toString(total),JLabel.CENTER);
            p.add(welcome);
            
            JButton viewShopCRT = new JButton("View Your Cart");
            p.add(viewShopCRT);
            
            JLabel cardNumberLabel = new JLabel("Please enter your Credit Card number: ", JLabel.TRAILING);
            p.add(cardNumberLabel);
            final JTextField cardNumberTF = new JTextField(10);
            cardNumberLabel.setLabelFor(cardNumberTF);
            p.add(cardNumberTF);
           
            JButton checkout = new JButton("Checkout");
            p.add(checkout);
            
            JLabel space = new JLabel("");
            p.add(space);

            JButton logout = new JButton("Log Out");
            p.add(logout);

            viewShopCRT.addActionListener(new viewShopCRT());
            logout.addActionListener(new logout());
            
            checkout.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    
                    for(Product x: cart){
                        Seller Vendor = pos.findSeller(x.getVendorName());  
                        Vendor = pos.findSeller(x.getVendorName());  
                        pos.bank.find(Vendor.getAccountNumber()).setBalance(x.getPrice()*qty.get(cart.indexOf(x)));
                    }
                    JFrame frame = new JFrame();
                    JOptionPane.showMessageDialog(frame, "Order went through!");
                    saveAll();
                    userHome(userNameTF.getText());
                    cart.clear();
                }
            });
            

            finishFrame();
        }
    }   
    /**
     * this frame allows the user to modify the
     * qty of a product in his cart
     */
    public class updateCRT implements ActionListener{
        public void actionPerformed(ActionEvent e){

            clearFrame();
            frame.setTitle("Update Cart");
        
            p= new JPanel (new BorderLayout());
            p2 = new JPanel(new BorderLayout());
        
            JButton viewShopCRT = new JButton("Shopping Cart");
            p2.add(viewShopCRT,BorderLayout.WEST);
        
            JButton logout = new JButton("Log Out");
            p2.add(logout,BorderLayout.EAST);
        
            DefaultListModel listModel = new DefaultListModel();
        
            for(Product x: cart)
            {
                listModel.addElement(x.getProductName());
            }
       
            final JList list = new JList(listModel);
        
            list.addListSelectionListener(new ListSelectionListener(){
                public void valueChanged(ListSelectionEvent e){
                productPage(cart.get(list.getSelectedIndex()));
                }
            });
        
         
        
            list.setVisibleRowCount(8);
            JScrollPane listScrollPane = new JScrollPane(list);
        
            viewShopCRT.addActionListener(new viewShopCRT());
            logout.addActionListener(new logout());
        
        
            p.add(listScrollPane,BorderLayout.CENTER);
            p.add(p2,BorderLayout.SOUTH);
        
        
            frame.add(p);
        
            finishFrame();    
        }
    }
            /**
             * will clear and show the product list form
             */
    public class viewProdList implements ActionListener{
        public void actionPerformed(ActionEvent e){

            clearFrame();
            showProductList();
        }
    }
            /**
             * will save all the info to the txt files and show the login frame.
             */
    public class logout implements ActionListener{
        public void actionPerformed(ActionEvent e){

            makeLoginFrame();
            saveAll();
        }
    }
    /**
     * Display the seller bank
     */
    public class viewBank implements ActionListener{
        public void actionPerformed(ActionEvent e){

            displayBank();
        }
    }
    /**
     *Display the seller inventory
     */
    public class viewInventory implements ActionListener{
        public void actionPerformed(ActionEvent e){

            clearFrame();
            showInventory();
        }
    } 
    /**
     * Displays proper login page based on input credentials
     */
    public class login implements ActionListener{
        public void actionPerformed(ActionEvent e){
            int credential = pos.login(userNameTF.getText(), String.copyValueOf(passwordTF.getPassword()));

            //user credentials
            if (credential == 1){
                user = pos.findUser(userNameTF.getText());
                clearFrame();
                userHome(userNameTF.getText());
            }

            //seller credentials
            else if (credential == 2){
                sellerHome(userNameTF.getText());
            }

            //credential error
            else{
                JFrame frame = new JFrame();
                JOptionPane.showMessageDialog(frame, "please enter a valid User Name and password.");
            }
        }
    } 
    /**
     * saves all lists to txt
     */
    public void saveAll(){
        pos.saveUserlist();
        pos.saveProductlist();
        pos.saveSellerlist();
        pos.saveBank();
        
    }
}
